import { memo, useState } from 'react'
import { Button, Popover, Paper } from "@mui/material"
import { useTranslation } from 'react-i18next'
import propTypes from 'prop-types'

const DangerousButton = (props) => {

  const { t } = useTranslation()

  const [anchorEl, setAnchorEl] = useState(null)
  const openPopover = (event) => {
    setAnchorEl(event.currentTarget)
  }

  const handleClose = () => {
    setAnchorEl(null)
  }

  const open = Boolean(anchorEl);

  const confirm = () => {
    if (props.confirm && typeof (props.confirm) === 'function') {
      props.confirm()
    }
  }

  return (
    <div className={`MuiButton-root ${props.className ? ' ' + props.className : ''}`} style={{ display: 'inline-flex', position: 'relative', ...props.style }}>
      <div onClick={openPopover}>
        {
          props.children ? props.children : (
            <Button size="small" variant={props.variant} color="error">{t('common.delete')}</Button>
          )
        }
      </div>
      <Popover open={open} anchorEl={anchorEl} onClose={handleClose}>
        <Paper style={{ bgcolor: 'background.paper', padding: '0px 0px 0px 8px' }}>
        {props.desc ? props.desc : t('common.confirmDelete')}
          <Button size="small" color="error" onClick={confirm}>{t('common.yes')}</Button>
        </Paper>
      </Popover>
    </div>
  )
}

DangerousButton.propTypes = {
  confirm: propTypes.func.isRequired,
  variant: propTypes.string
}

DangerousButton.defaultProps = {
  variant: 'text'
}

export default memo(DangerousButton)